package com.qk.manangement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.common.context.UserContext;
import com.qk.common.response.ClueByIdResponse;
import com.qk.common.response.CluePoolPageResponse;
import com.qk.common.response.PageResult;
import com.qk.entity.pojo.*;
import com.qk.entity.request.clue.ClueUpdateRequest;
import com.qk.entity.request.clue.FalseClueRequest;
import com.qk.manangement.mapper.BusinessMapper;
import com.qk.manangement.mapper.ClueTrackRecordMapper;
import com.qk.manangement.service.ClueService;
import com.qk.manangement.mapper.ClueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue>
        implements ClueService {

    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private ClueTrackRecordMapper clueTrackRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public PageResult<Clue> PageList(Integer clueId, String phone, Integer status, Integer channel, String assignName, Integer page, Integer pageSize) {
        // 参数校验
        if (ObjectUtil.isNull(page) || ObjectUtil.isNull(pageSize)) {
            return new PageResult<>(0L, List.of());
        }

        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询数据
        List<Clue> list = clueMapper.pageList(clueId, phone, status, channel, assignName);

        // 构建分页结果
        PageInfo<Clue> pageInfo = new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }


    @Override
    public boolean add(Clue clue) {
        // 参数校验
        if (ObjectUtil.isNull(clue)) {
            return false;
        }

        // 校验必要字段
        if (StrUtil.isBlank(clue.getPhone()) || ObjectUtil.isNull(clue.getChannel())) {
            return false;
        }

        // 设置创建和更新时间
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());

        // 保存线索
        return clueMapper.add(clue);
    }


    @Override
    public boolean assign(Integer clueId, Integer userId) {
        // 参数校验
        if (ObjectUtil.isNull(clueId) || ObjectUtil.isNull(userId)) {
            return false;
        }

        // 验证用户和线索是否存在
        if (ObjectUtil.isNull(Db.getById(userId, User.class)) ||
                ObjectUtil.isNull(Db.getById(clueId, Clue.class))) {
            return false;
        }

        // 更新线索分配信息
        Clue clue = new Clue();
        clue.setId(clueId);
        clue.setUserId(userId);
        clue.setStatus(2);
        clue.setUpdateTime(LocalDateTime.now());

        return clueMapper.updateById(clue) > 0;
    }


    @Override
    @Transactional
    public boolean falseClue(Integer id, FalseClueRequest falseClueRequest) {
        // 参数校验
        if (ObjectUtil.isNull(id) || ObjectUtil.isNull(falseClueRequest)) {
            return false;
        }

        // 验证线索是否存在
        if (ObjectUtil.isNull(getById(id))) {
            return false;
        }

        // 更新线索状态
        Clue clue = new Clue();
        clue.setId(id);
        clue.setStatus(4);
        clue.setUpdateTime(LocalDateTime.now());
        clueMapper.updateById(clue);

        // 创建线索跟踪记录
        ClueTrackRecord trackRecord = ClueTrackRecord.builder()
                .clueId(id)
                .userId(UserContext.getUserId())
                .type(0)
                .falseReason(falseClueRequest.getReason())
                .record(falseClueRequest.getRemark())
                .createTime(LocalDateTime.now())
                .build();
        clueTrackRecordMapper.insert(trackRecord);

        return true;
    }


    @Override
    @Transactional
    public boolean toBusiness(Integer id) {
        // 参数校验
        if (ObjectUtil.isNull(id)) {
            return false;
        }

        // 获取线索信息
        Clue dbClue = getById(id);
        if (ObjectUtil.isNull(dbClue)) {
            return false;
        }

        // 创建商机
        Business business = new Business();
        BeanUtil.copyProperties(dbClue, business, "id", "createTime", "updateTime");
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(1);
        business.setClueId(id);
        businessMapper.insert(business);

        // 更新线索状态
        Clue clue = new Clue();
        clue.setId(id);
        clue.setStatus(5);
        clue.setUpdateTime(LocalDateTime.now());
        return clueMapper.updateById(clue) > 0;
    }


    @Override
    public ClueByIdResponse getByIdMy(Integer id) {
        // 参数校验
        if (ObjectUtil.isNull(id)) {
            return null;
        }

        // 查询线索信息
        Clue clue = clueMapper.selectById(id);
        if (ObjectUtil.isNull(clue)) {
            return null;
        }

        // 获取跟踪记录
        List<TrackRecords> trackRecords = clueMapper.getTrackRecordsByClueId(clue.getId());

        // 构建返回结果
        ClueByIdResponse response = BeanUtil.copyProperties(clue, ClueByIdResponse.class);
        response.setTrackRecords(trackRecords);

        return response;
    }


    @Override
    @Transactional
    public boolean updateClue(ClueUpdateRequest clueUpdateRequest) {
        // 参数校验
        if (ObjectUtil.isNull(clueUpdateRequest)) {
            return false;
        }

        // 校验必要字段
        if (ObjectUtil.isNull(clueUpdateRequest.getId()) ||
                StrUtil.isBlank(clueUpdateRequest.getPhone()) ||
                ObjectUtil.isNull(clueUpdateRequest.getChannel())) {
            return false;
        }

        // 更新线索信息
        this.baseMapper.update(Wrappers.lambdaUpdate(Clue.class)
                .set(Clue::getActivityId, clueUpdateRequest.getActivityId())
                .set(Clue::getName, clueUpdateRequest.getName())
                .set(Clue::getGender, clueUpdateRequest.getGender())
                .set(Clue::getAge, clueUpdateRequest.getAge())
                .set(Clue::getWechat, clueUpdateRequest.getWechat())
                .set(Clue::getQq, clueUpdateRequest.getQq())
                .set(Clue::getUserId, UserContext.getUserId())
                .set(Clue::getStatus, 3)
                .set(Clue::getSubject, clueUpdateRequest.getSubject())
                .set(Clue::getLevel, clueUpdateRequest.getLevel())
                .set(Clue::getNextTime, clueUpdateRequest.getNextTime())
                .set(Clue::getUpdateTime, LocalDateTime.now())
                .eq(Clue::getId, clueUpdateRequest.getId()));

        // 创建线索跟踪记录
        ClueTrackRecord trackRecord = ClueTrackRecord.builder()
                .clueId(clueUpdateRequest.getId())
                .userId(UserContext.getUserId())
                .subject(clueUpdateRequest.getSubject())
                .level(clueUpdateRequest.getLevel())
                .record(clueUpdateRequest.getRecord())
                .nextTime(clueUpdateRequest.getNextTime())
                .createTime(LocalDateTime.now())
                .type(1)
                .build();

        clueTrackRecordMapper.insert(trackRecord);
        return true;
    }


    @Override
    public PageResult PagePoolList(Integer clueId, String phone, Integer channel, Integer page, Integer pageSize) {
        // 参数校验
        if (ObjectUtil.isNull(page) || ObjectUtil.isNull(pageSize)) {
            return new PageResult<>(0L, List.of());
        }

        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询数据
        List<CluePoolPageResponse> cluePoolPageResponses = clueMapper.pagePoolList(clueId, phone, channel);

        // 构建分页结果
        PageInfo<CluePoolPageResponse> pageInfo = new PageInfo<>(cluePoolPageResponses);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }


}




